package com.example.bookstore.web;

import com.example.bookstore.pojo.User;
import com.example.bookstore.service.UserService;
import com.example.bookstore.service.impl.UserServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;


//目前不使用————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");
        System.out.println(code);

        if ("bnbnb".equalsIgnoreCase(code)) {
            try {
                if (!userService.existUsername(username)) {
                    userService.registerUser(new User(username,password,email));
                    req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
                } else {//用户名已存在
                    System.out.println("用户名已存在");
                    //显示回显信息
                    req.setAttribute("msg","用户名已存在");
                    req.setAttribute("username",username);
                    req.setAttribute("email",email);

                    req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } else {//验证码不正确
            System.out.println("验证码错误");
            //显示回显信息
            req.setAttribute("msg","验证码错误");
            req.setAttribute("username",username);
            req.setAttribute("email",email);

            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }



//    private String message;
//
//    public void init() {
//        message = "Hello World!";
//    }
//
//    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        response.setContentType("text/html");
//
//        // Hello
//        PrintWriter out = response.getWriter();
//        out.println("<html><body>");
//        out.println("<h1>" + message + "</h1>");
//        out.println("</body></html>");
//    }
}
